import dayjs from 'dayjs';
import getFilesInfoSystem from './getFilesInfoSystem';
export default async ({
  fileInfo = {},
  db = {},
  dirPath = '',
  checkedStatus = '',
}) => {
  const dirArr = dirPath.split('/');
  dirArr.pop();
  const pPath = dirArr.join('/');

  const checked = ['All', 'Part'].includes(checkedStatus);
  try {
    const doc = {
      ...fileInfo,
      pPath: pPath,
      path: dirPath,
      checked: checked,
    };
    await db.updateAsync(
      {path: dirPath},
      {$set: doc},
      {
        upsert: true,
      },
    );
  } catch (e) {
    console.log('异常', e.message);
  }
  // try {
  //   const doc = await db.findOneAsync({path: dirPath});
  //   // console.log(doc);
  // } catch (e) {
  //   console.log('异常', e.message);
  // }

  //所有子孙目录
  let total = 0;
  const depthSetFiles = async pPath => {
    try {
      const systemFiles = await getFilesInfoSystem({pPath});

      const dirs = systemFiles.filter(item => item.type === 'directory');
      if (pPath === dirPath) {
        try {
          const doc = {
            son_total: dirs.length,
          };
          await db.updateAsync(
            {path: dirPath},
            {$set: doc},
            {
              upsert: true,
            },
          );
        } catch (e) {
          console.log('异常', e.message);
        }
      }

      for (const item of new Set(dirs)) {
        total++;
        // console.log(total, item.path);
        try {
          const doc = {
            ...item,
            checked: checked,
          };
          await db.updateAsync(
            {path: item.path},
            {$set: doc},
            {
              upsert: true,
            },
          );
        } catch (e) {
          console.log('异常', e.message);
        }
      }
      try {
        const doc = {
          des_total: total,
        };
        await db.updateAsync(
          {path: dirPath},
          {$set: doc},
          {
            upsert: true,
          },
        );
      } catch (e) {
        console.log('异常', e.message);
      }

      for (const item of new Set(dirs)) {
        depthSetFiles(item.path);
      }
    } catch (e) {
      console.log('异常', e.message);
    }
  };
  depthSetFiles(dirPath);

  // //祖先目录
  // try {
  //   let newPath = '';
  //   for (const filename of new Set(dirArr)) {
  //     if (filename && filename !== 'sdcard') {
  //       newPath += `/${filename}`;
  //       console.log('newPath', newPath);
  //       const count = await db.countAsync({path: new RegExp(`^${newPath}.+`)});
  //       console.log('count', count);
  //       // const doc = {
  //       //   path: newPath,
  //       //   des_checked: true,
  //       // };
  //       // await db.updateAsync({path: newPath}, doc, {
  //       //   upsert: true,
  //       // });
  //     }
  //   }
  // } catch (e) {
  //   console.log('异常', e.message);
  // }
};
